package com.chengh.nami.core.security.service;

import com.chengh.nami.common.constants.CacheConstants;
import com.chengh.nami.common.domain.model.LoginUserEntity;
import com.chengh.nami.common.domain.properties.AuthProperties;
import com.chengh.nami.common.utils.ServletUtils;
import com.chengh.nami.common.utils.StringUtils;
import com.chengh.nami.common.utils.ip.AddressUtils;
import com.chengh.nami.common.utils.ip.IpUtils;
import com.chengh.nami.common.utils.redis.RedisCache;
import com.chengh.nami.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author chengh
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenService {

    /**
     * 1秒的毫秒数
     */
    protected static final long MILLIS_SECOND = 1000;

    /**
     * 1分钟的毫秒数
     */
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    /**
     * 20分钟的毫秒数
     */
    private static final Long MILLIS_MINUTE_TEN = 10 * 60 * 1000L;

    private final AuthProperties authProperties;

    private final RedisCache redisCache;

    public String createToken(LoginUserEntity loginUserEntity) {
        String uuid = IdUtils.fastUUID();
        loginUserEntity.setToken(uuid);
        setUserAgent(loginUserEntity);
        refreshToken(loginUserEntity);
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(authProperties.getTokenPrefix(), uuid);
        return createToken(claims);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUserEntity 登陆信息
     */
    public void setUserAgent(LoginUserEntity loginUserEntity) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUserEntity.setIpaddr(ip);
        loginUserEntity.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUserEntity.setBrowser(userAgent.getBrowser().getName());
        loginUserEntity.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUserEntity 登录信息
     */
    public void refreshToken(LoginUserEntity loginUserEntity) {
        // 获取当前时间的毫秒
        loginUserEntity.setLoginTime(System.currentTimeMillis());
        // 失效时间 毫秒
        loginUserEntity.setExpireTime(loginUserEntity.getLoginTime() + authProperties.getExpiration() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUserEntity.getToken());
        redisCache.setCacheObject(userKey, loginUserEntity, authProperties.getExpiration(), TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, authProperties.getSecret()).compact();
    }

    public LoginUserEntity getSelUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(authProperties.getTokenPrefix());
                String userKey = getTokenKey(uuid);
                log.info("读取redis,key{}", userKey);
                return redisCache.getCacheObject(userKey);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(authProperties.getTokenHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(authProperties.getTokenPrefix())) {
            token = token.replace(authProperties.getTokenPrefix(), "");
        }
        return token;
    }

    /**
     * 验证令牌有效期，相差不足设置分钟，自动刷新缓存
     */
    public void verifyToken(LoginUserEntity selUser) {
        long expireTime = selUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(selUser);
        }
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(authProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 删除用户在缓存中的身份信息
     *
     * @param token token值
     */
    public void delSelUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }
}
